package com.wsoft.hr.pm.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONObject;
import com.wsoft.constant.CommonConstant;
import com.wsoft.core.service.CommonFreemarkerService;
import com.wsoft.core.service.CommonMemberService;
import com.wsoft.core.vo.MemberVO;
import com.wsoft.hr.pm.entity.HrPmWarningEntity;
import com.wsoft.hr.pm.entity.sys.HrMemberOrgRelationEntity;
import com.wsoft.hr.pm.enums.ProcessCardTypeEnum;
import com.wsoft.hr.pm.enums.WarningTypeEnum;
import com.wsoft.hr.pm.manager.HrMemberOrgRelationManager;
import com.wsoft.hr.pm.manager.HrPmWarningManager;
import com.wsoft.hr.pm.mapper.HrPmWarningMapper;
import com.wsoft.hr.pm.vo.warning.ProgressLagWarningVO;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 自评预警
 * @Author z001
 * @Date 2025/3/8 09:46
 */
@Service
public class SelfEvaluationWaringJob implements Job {

    @Resource
    private HrPmWarningMapper warningMapper;
    @Resource
    private HrMemberOrgRelationManager relationManager;
    @Resource
    private HrPmWarningManager warningManager;
    @Resource
    private CommonMemberService memberService;
    @Resource
    private CommonFreemarkerService freemarkerService;
    /**
     * 模版code
     */
    private final String FREEMARKER_CODE = "freemarker_code";

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        JobDetail job = jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap = job.getJobDataMap();
        //任务参数
        Object jobParam = jobDataMap.get(CommonConstant.JOB_PARAMS);
        if (ObjUtil.isNull(jobParam)) {
            return;
        }
        JSONObject param = JSONObject.parseObject(jobParam.toString());
        //获取模版code
        Object freemarkerCode = param.get(FREEMARKER_CODE);
        if (null == freemarkerCode) {
            return;
        }


        String lastMonthDate = getLastMonthDate();
        List<ProgressLagWarningVO> voList = warningMapper.selectMemberTemplateScore(lastMonthDate, ProcessCardTypeEnum.SELF_EVALUATION_CARD.getType());
        if(CollUtil.isEmpty(voList)){
            return;
        }

        List<Long> memberIds = voList.stream().map(ProgressLagWarningVO::getMemberId).collect(Collectors.toList());
        List<HrMemberOrgRelationEntity> relationList = relationManager.getByMemberIsd(memberIds);
        Map<Long, Long> relationMap = relationList.stream().collect(Collectors.toMap(HrMemberOrgRelationEntity::getMemberId ,HrMemberOrgRelationEntity::getHrOrgId));


        List<HrPmWarningEntity> warningList = new ArrayList<>();
        for (ProgressLagWarningVO warningVO : voList) {
            HrPmWarningEntity warning = new HrPmWarningEntity();
            warning.setTitle(buildFreemarkerMap(warningVO,freemarkerCode));
            warning.setType(WarningTypeEnum.PROCESS_BLOCKAGE.getType());
            warning.setHrOrgId(relationMap.get(warningVO.getMemberId()));
            warning.setOpenType("component");
            warning.setOpenPage("");
            warningList.add(warning);
        }
        warningManager.saveBatch(warningList);

    }

    /**
     * 构建freemarker模板
     * @param vo
     * @param freemarkerCode
     * @return
     */
    private String buildFreemarkerMap(ProgressLagWarningVO vo, Object freemarkerCode){
        MemberVO memberVO = memberService.getMemberInfo(vo.getMemberId());
        Map<String,Object> map = new HashMap<>(3);
        map.put("memberName",memberVO.getName());
        map.put("templateName",vo.getTemplateName());
        //${memberName}${templateName}尚未自评，即将超时，请及时确认。
        return freemarkerService.sendTextTemplate(freemarkerCode.toString(), map,true);
    }


    /**
     * 获取当前时间的上个月日期，格式为 yyyy-MM
     *
     * @return 上个月的日期，格式为 yyyy-MM
     */
    public static String getLastMonthDate() {
        // 获取当前时间
        Date now = DateUtil.date();

        // 获取下个月的日期
        Date nextMonth = DateUtil.offsetMonth(now, -1);

        // 格式化为 yyyy-MM
        return DateUtil.format(nextMonth, "yyyy-MM");
    }
}
